<?php

if (! function_exists('sendVerifyCode')) {
    function sendVerifyCode($mobile,$mobile_code) {
        $send_result = \App\ZL\ORG\Aliydx\Sms::sendSms(
            "你好菜果蔬生鲜", // 短信签名
            "SMS_113620021", // 短信模板编号
            $mobile, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$mobile_code,
            ),
            "123"   // 流水号,选填
        );
        if(isset($send_result->Code) && $send_result->Code=="OK"){
            $status = 1;
            $msg = '验证码发送成功！';
//            session(['verify_tel_code'=>$mobile_code]);
//            session(['verify_tel'=>$mobile]);
        }else{
            $status = 0;
//            $msg = '验证码发送失败！';
            $msg = $send_result->Message?$send_result->Message:'验证码发送失败！';
        }
        return \App\ZL\ResponseLayout::apply($status,false,$msg);
    }
}


if (! function_exists('getTitleByArray')) {
    function getTitleByArray($res,$modelArray,$dicArray,$dictionaries,$foreach=true)
    {
        $dict_array = [];
        foreach ($dicArray as $k=>$item) {
            $dict_array[$k] = $dictionaries->getByType($item);
        }
//        dd($dict_array);
        if($foreach){
            foreach ($res as $re) {
                foreach ($modelArray as $k=>$item) {
                    $_title = $item.'_title';
                    $re->$_title = $dict_array[$k][$re->$item]->text;
                }
            }
        }else{
            foreach ($modelArray as $k=>$item) {
                $_title = $item.'_title';
                $res->$_title = $dict_array[$k][$res->$item]->text;
            }
        }
        return $res;
    }
}

if (! function_exists('computeHour')) {
    function computeHour($time1,$time2)
    {
        $time1Array = explode(':',$time1);
        $time2Array = explode(':',$time2);
        $differenceValue1 = $time2Array[0]-$time1Array[0];
        $differenceValue2 = $time2Array[1]-$time1Array[1];
        return $differenceValue1+($differenceValue2/60);
    }
}

if (! function_exists('objToArray')) {
    function objToArray($array)
    {
        return json_decode(json_encode($array),true);
    }
}

if (! function_exists('triggerClassAddEvent')) {
    function triggerClassAddEvent($user,$class,$date,$handler_name=false)
    {
        $handler_name = $handler_name?$handler_name:Auth::user()->name;
    }
}

if (! function_exists('request_post')) {
    function request_post($url,$post_data = array()) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        $output = curl_exec($ch);
        curl_close($ch);


        return $output;
    }
}

if (! function_exists('getWeekDays')) {
    function getWeekDays()
    {
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+1,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+2,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+3,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+4,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+5,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+6,date("Y")));
        $data[] = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
        return $data;
    }
}

if (! function_exists('getConfigValue')) {
    function getConfigValue($type)
    {
        if($value = \Illuminate\Support\Facades\Cache::get('config_'.$type, null)){
            return $value;
        }
        else{
            $value = \Illuminate\Support\Facades\DB::table('configs')->where('type',$type)->first()->value;
            \Illuminate\Support\Facades\Cache::put('config_'.$type, $value, 60);
            return $value;
        }
    }
}
if (! function_exists('responseZK')) {
    function responseZK($errCode=1,$data = [],$msg = '',$other=array())
    {
        return response()->json(\App\ZL\ResponseLayout::apply($errCode,$data,$msg,$other));
    }
}
//获取sessionid
if (! function_exists('getSessionId')) {
    function getSessionId()
    {
        $session_id = request()->header('session-id');
        if($session_id){
            return $session_id;
        }
        $session_id = request()->get('session_id');
        if($session_id){
            return $session_id;
        }
        return null;
    }
}
//获取秘钥字符串
if (! function_exists('getAuthToken')) {
    function getAuthToken()
    {
        $authToken = request()->header('auth-token');
        if($authToken){
            return $authToken;
        }
        $authToken = request()->get('auth_token');
        if($authToken){
            return $authToken;
        }
    }
}
//提取session数据
if (! function_exists('getSessionData')) {
    function getSessionData()
    {
        if(getSessionId())
            return json_decode(cache(getSessionId()),true);
        else
            return null;
    }
}
//设置session数据
if (! function_exists('setSessionData')) {
    function setSessionData($data)
    {
        cache([getSessionId()=>json_encode($data)],isset($data['expires_in'])?$data['expires_in']:7200);
    }
}
//添加 session数据
if (! function_exists('addSessionData')) {
    function addSessionData($data)
    {
        $old = getSessionData();
        if($old){
            $new = array_merge($old,$data);
        }else{
            $new = $data;
        }
        setSessionData($new);
    }
}
//解密数据保存到session
if (! function_exists('decodeToSession')) {
    function decodeToSession()
    {
        $session_data = getSessionData();
        $token = getAuthToken();
        $key = config('app.aes_key');
        $iv = config('app.aes_iv');
        $json_str = \App\ZL\Library\Openssl::decryptByAes($key,$iv,$token);
        $encrypted = json_decode($json_str,true);

        $session_data = $session_data?$session_data:[];
        $encrypted = $encrypted?$encrypted:[];
        $all = array_merge($session_data,$encrypted);
        setSessionData($all);
        return $all;
    }
}
//获取session和秘钥 公共的数据
if (! function_exists('getSessionAllData')) {
    function getSessionAllData()
    {
        $session_data = getSessionData();
        if(isset($session_data['id'])){
            return $session_data;
        }else{
            return decodeToSession();
        }
    }
}

//获取session和秘钥 公共的数据 并且取出单一字段
if (! function_exists('getSessionField')) {
    function getSessionField($field)
    {
        $data = getSessionAllData();
        return isset($data[$field])?$data[$field]:null;
    }
}

//存入notification
if (! function_exists('saveNotification')) {
    function saveNotification($data,$title='msg')
    {
        $data = json_encode($data,256);
        
        \Illuminate\Support\Facades\DB::table('notifications')->insert([
            ['json' => $data, 'title' => $title, 'created_at' => date('Y-m-d H:i:s')],
        ]);
    }
}


if( ! function_exists('getArrayByStr')){
    function getArrayByStr($str, $segmentation = ',')
    {
        if(is_array($str)){
            $arr = $str;
        }else{
            $arr = explode($segmentation,$str);
        }
        return $arr;
    }
}

if( ! function_exists('getArrayByArray')){
    function getArrayByArray($array, $field = 'id',$is_array=1)
    {
        $new = [];
        foreach ($array as $item) {
            $new[] = $item[$field];
        }
        return $is_array?$new:implode(',',$new);
    }
}

if( ! function_exists('getIP')){
    //获取真实ip
    function getIP(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }
}

if(!function_exists('getOrderTracesByJson')){
    //电商ID
    defined('EBusinessID') or define('EBusinessID', 1261234);
//电商加密私钥，快递鸟提供，注意保管，不要泄漏
    defined('kdniao_AppKey') or define('kdniao_AppKey', '9ba7c900-0473-4572-ba63-7391b36fdf11');
//请求url
    defined('kdniao_ReqURL') or define('kdniao_ReqURL', 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx');

    /**
     * Json方式 查询订单物流轨迹
     */
    function getOrderTracesByJson($LogisticCode='',$ShipperCode='',$OrderCode=''){
        $requestData= "{'OrderCode':'','ShipperCode':'$ShipperCode','LogisticCode':'$LogisticCode'}";

        $datas = array(
            'EBusinessID' => EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = encrypt1($requestData, kdniao_AppKey);
        $result=sendPost(kdniao_ReqURL, $datas);

        //根据公司业务处理返回的信息......
        return $result;
    }

    /**
     * XML方式 查询订单物流轨迹
     */
    function getOrderTracesByXml(){
        $requestData= "<?xml version=\"1.0\" encoding=\"utf-8\" ?>".
            "<Content>".
            "<OrderCode></OrderCode>".
            "<ShipperCode>SF</ShipperCode>".
            "<LogisticCode>589707398027</LogisticCode>".
            "</Content>";

        $datas = array(
            'EBusinessID' => EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '1',
        );
        $datas['DataSign'] = encrypt1($requestData, kdniao_AppKey);
        $result=sendPost(kdniao_ReqURL, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    function encrypt1($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }


    function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(!isset($url_info['port']))
        {
            $url_info['port']=80;
        }
        // echo $url_info['port'];
        $httpheader = "POST " . $url . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }
}

if (! function_exists('postCurl')) {
    function postCurl($url,$post,$cookie=null){//get https的内容
        $post_str = '';
        foreach ($post as $k=>$v) {
            $post_str = empty($post_str)?$post_str:$post_str.'&';
            $post_str .= $k.'='.urlencode($v);
        }
        $ch = curl_init();//新建curl
        curl_setopt($ch, CURLOPT_URL, $url);//url
        curl_setopt($ch, CURLOPT_POST, 1);  //post
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);//post内容
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        if($cookie)
            curl_setopt($ch,CURLOPT_COOKIE,$cookie);
        $res =  curl_exec($ch); //输出
        $arr= json_decode($res,true);
        curl_close($ch);
        return $arr;
    }
}

if (! function_exists('getPrice')) {
    function getPrice($goods){
        if($goods instanceof \Illuminate\Support\Collection){
            $goods = $goods->toArray();
        }
        if($goods->sale_price>0)
            return $goods->sale_price;
        else
            return $goods->marker_price;
    }
}

/*
*lock_thisfile：获得独享锁
*@param $tmpFileStr 用来作为共享锁文件的文件名（可以随便起一个名字）
*@param $locktype 锁类型，缺省为false(非阻塞型，也就是一旦加锁失败则直接返回false),设置为true则会一直等待加锁成功才返回
*@return 如果加锁成功，则返回锁实例(当使用unlock_thisfile方法的时候需要这个参数)，加锁失败则返回false.
*/
function lock_thisfile($tmpFileStr,$locktype=false){
    if($locktype == false)
        $locktype = LOCK_EX|LOCK_NB;
    else
        $locktype = LOCK_EX;
    $can_write = 0;
    $lockfp = @fopen($tmpFileStr.".lock","w");
    if($lockfp){
        $can_write = @flock($lockfp,$locktype);
    }
    if($can_write){
        return $lockfp;
    }
    else{
        if($lockfp){
            @fclose($lockfp);
            @unlink($tmpFileStr.".lock");
        }
        return false;
    }
}

/**
 *unlock_thisfile：对先前取得的锁实例进行解锁
 *@param $fp lock_thisfile方法的返回值
 *@param $tmpFileStr 用来作为共享锁文件的文件名（可以随便起一个名字）
 */
function unlock_thisfile($fp,$tmpFileStr){
    @flock($fp,LOCK_UN);
    @fclose($fp);
    @fclose($fp);
    @unlink($tmpFileStr.".lock");
}

function zhong_wen_math($string,$code ='UTF-8'){
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    } else {
        $pa = "/[\x01-\x7f]|[\xa1-\xff][\xa1-\xff]/";
    }
    preg_match_all($pa, $string, $t_string);
    $math=[];
    foreach($t_string[0] as $k=>$s){
        $math[]=$s;
    }
    return $math;
}

function get_shop(){
    if(\Illuminate\Support\Facades\Auth::guard('admin')->check()){
        return \Illuminate\Support\Facades\Auth::guard('admin')->user()->shop;
    }else{
        return null;
    }
}